package com.zrl.project.common;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.zrl.project.constant.RedisConstants;
import com.zrl.project.exception.BusinessException;
import com.zrl.project.model.entity.User;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: zrl
 * @date: 2022/11/9 20:45
 * @description:
 */

public class RefreshInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    public RefreshInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token
        String token =request.getHeader("authorization");
        if (StrUtil.isBlank(token)){
            return true;
        }
        //2.获取redis中的用户
        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().
                entries(tokenKey);

        //3.判断用户是否存在
        if (userMap.isEmpty()){
            return true;
        }
        User user = BeanUtil.fillBeanWithMap(userMap, new User(), false);
        user.setUserPassword("*");
        //6.存在，保存用户信息到ThreadLocal
        UserHolder.saveUser(user);
        //7.刷新token有效期
        stringRedisTemplate.expire(tokenKey,RedisConstants.LOGIN_USER_TTL, TimeUnit.SECONDS);
        //8.放行
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }

    /**
     * 用户脱敏
     * @param originalUser 用户
     * @return
     */
    public User getSafetyUser(User originalUser) {
        if(originalUser == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户不存在");
        }
        User safetyUser = new User();
        safetyUser.setId(originalUser.getId());
        safetyUser.setUserName(originalUser.getUserName());
        safetyUser.setUserAccount(originalUser.getUserAccount());
        safetyUser.setUserAvatar(originalUser.getUserAvatar());
        safetyUser.setGender(originalUser.getGender());
        safetyUser.setRole(originalUser.getRole());
        safetyUser.setPhone(originalUser.getPhone());
        safetyUser.setEmail(originalUser.getEmail());
        safetyUser.setUserStatus(originalUser.getUserStatus());
        safetyUser.setCreateTime(originalUser.getCreateTime());
        safetyUser.setSign(originalUser.getSign());
        return safetyUser;
    }
}
